<template>
    <div class="students">
        <el-row>
            <!-- 每一行所有的列数总和为24 -->

            <!-- 班级列表 -->
            <el-col :span="5">
                <h3 style="text-align: center;">班级列表</h3>
                <!-- 树形控件默认展示的属性为label和 -->
                <el-tree ref="classTreeRef" :data="classList" :props="{ label: 'className' }"
                    @node-click="handleTreeClick" highlight-current node-key="classId"></el-tree>
            </el-col>
            <el-col :span="18" :offset="1">
                <!-- 筛选 -->
                <el-form ref="queryFormRef" :model="queryForm" inline size="mini">
                    <el-form-item label="学号" prop="stuNum">
                        <el-input v-model="queryForm.stuNum"></el-input>
                    </el-form-item>
                    <el-form-item label="姓名" prop="stuName">
                        <el-input v-model="queryForm.stuName"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号码" prop="phone">
                        <el-input v-model="queryForm.phone"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                        <el-button type="info" @click="rest">重置</el-button>
                    </el-form-item>
                </el-form>

                <!-- 添加 -->
                <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAdd">添加</el-button>

                <!-- 表格 -->
                <el-table :data="stuList" style="width: 100%">
                    <el-table-column type="index" label="#" width="50" align="center">
                    </el-table-column>
                    <el-table-column prop="stuNum" label="学号" align="center" width="120">
                    </el-table-column>
                    <el-table-column prop="stuName" label="姓名" align="center" width="120">
                    </el-table-column>
                    <el-table-column prop="majorId" label="专业" align="center" width="120">
                        <template #default="{ row }">{{ getMajorLabel(row.majorId) }}</template>
                    </el-table-column>
                    <el-table-column prop="phone" label="手机" align="center" width="120">
                    </el-table-column>
                    <el-table-column prop="age" label="年龄" align="center">
                    </el-table-column>
                    <el-table-column prop="sex" label="性别" align="center">
                        <template #default="{ row }">{{ getSexLabel(row.sex) }}</template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="updateTime" label="修改时间" align="center" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column align="center" label="操作" width="180">
                        <template #default="{ row }">
                            <el-button type="text" icon="el-icon-edit" @click="handleEdit(row)">编辑</el-button>
                            <el-button type="text" icon="el-icon-delete" @click="handleDelete(row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <el-row type="flex" justify="center" style="margin-top: 10px;">
                    <el-pagination layout="prev, pager, next" :total="paginate.total"
                        :page-size.sync="paginate.pageSize" :current-page.sync="paginate.pageNum"
                        @current-change="handleCurrentPage">
                    </el-pagination>
                </el-row>

            </el-col>


            <!-- 弹窗 -->
            <el-dialog :visible.sync="dialog.visible" width="25%" @close="handleClose">
                <template #title>{{ dialog.isEdit ? "编辑学生" : "添加学生" }}</template>
                <el-form width="80px" label-position="top" size="small" :model="dialog.form" :rules="dialog.rules"
                    ref="dialogFormRef">
                    <el-form-item label="班级" prop="classId">
                        <el-select :value="dialog.form.classId" disabled>
                            <!-- label 选项名称 -->
                            <!-- value 选中当前选项的值 -->
                            <el-option v-for="item in classList" :key="item.classId" :label="item.className"
                                :value="item.classId"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="姓名" prop="stuName">
                        <el-input v-model="dialog.form.stuName"></el-input>
                    </el-form-item>

                    <el-form-item label="学号" prop="stuNum">
                        <el-input v-model="dialog.form.stuNum"></el-input>
                    </el-form-item>

                    <el-form-item label="手机号码" prop="phone">
                        <el-input v-model="dialog.form.phone"></el-input>
                    </el-form-item>

                    <el-form-item label="性别" prop="sex">
                        <el-select v-model="dialog.form.sex">
                            <el-option v-for="item in sexDictList" :key="item.dictValue" :label="item.dictLabel"
                                :value="item.dictValue"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="专业" prop="majorId">
                        <el-select v-model="dialog.form.majorId">
                            <el-option v-for="item in majorList" :key="item.majorId" :label="item.majorName"
                                :value="item.majorId"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="年龄" prop="age">
                        <el-input-number v-model="dialog.form.age" :min="0"></el-input-number>
                    </el-form-item>

                </el-form>

                <span slot="footer" class="dialog-footer">
                    <el-button size="small" @click="handleClose">取 消</el-button>
                    <el-button type="primary" size="small" @click="handleSubmit">确 定</el-button>
                </span>


            </el-dialog>
        </el-row>
    </div>
</template>

<script>
import { listClass } from '@/api/classes';
import { listStudents, delStudents, addStudents, updateStudents } from '@/api/students';
import { listMajor, listDictType } from '@/api/common';
import { checkQueryInput, restForm } from '@/utils/tools.js';

export default {
    name: 'Students',
    data() {
        return {
            // 班级数据
            classList: [],
            // 当前班级信息
            curClass: {},

            // 筛选
            queryForm: {
                stuNum: undefined,
                stuName: undefined,
                phone: undefined,
            },

            //分页
            paginate: {
                pageSize: 8,//每页的数量
                pageNum: 1,//第几页
                total: 0,//总数
            },

            // 学生信息
            stuList: [],

            // 专业
            sexDictList: [],
            // 性别
            majorList: [],

            // 弹窗
            dialog: {
                isEdit: false,//是否为编辑状态
                visible: false,
                form: {
                    classId: undefined,
                    stuName: undefined,
                    stuNum: undefined,
                    phone: undefined,
                    sex: undefined,
                    majorId: undefined,
                    age: undefined,
                },
                rules: {
                    classId: [{
                        required: true,
                        message: "请选择班级",
                        trigger: "blur"
                    }],
                    stuName: [{
                        required: true,
                        message: "请输入姓名",
                        trigger: "blur"
                    }],
                    stuNum: [{
                        required: true,
                        message: "请输入学号",
                        trigger: "blur"
                    }],
                    phone: [{
                        required: true,
                        message: "请输入手机号码",
                        trigger: "blur"
                    }],
                    sex: [{
                        required: true,
                        message: "请选择性别",
                        trigger: "blur"
                    }],
                    majorId: [{
                        required: true,
                        message: "请选择专业",
                        trigger: "blur"
                    }],
                    age: [{
                        required: true,
                        message: "请输入年龄",
                        trigger: "blur"
                    }],
                },
            },

        }
    },

    computed: {
        // 专业转换
        getMajorLabel() {
            return majorId => {
                const { majorName } = this.majorList.find(item => item.majorId === majorId) || {}
                return majorName || "-"
            }
        },
        // 性别转换
        getSexLabel() {
            return sexCode => {
                const { dictLabel } = this.sexDictList.find(item => item.dictValue === sexCode) || {}
                return dictLabel || "-"
            }
        },
    },

    created() {
        this.getListClass()
        // this.getListStudent()
        // this.getInit()
        this.getPromiseAll()
    },
    methods: {
        // 获取专业和字典值
        getPromiseAll() {
            Promise.all([listMajor(), listDictType("sys_user_sex")]).then(res => {
                console.log(res);
                const [majorRes, sexDictRes] = res
                this.majorList = majorRes.data
                this.sexDictList = sexDictRes.data
            })
        },



        // 获取班级列表
        // 方法一：
        // async getInit() {
        //     const classRes = await listClass()
        //     this.classList=classRes.data

        //         //获取第一条班级信息
        //         this.curClass = res.data[0]
        //         const {classId}=this.curClass
        //         const stuRes=await listStudents({...this.paginate,classId})
        // },

        // 方法二:
        getListClass() {
            listClass().then(res => {

                this.classList = res.data

                //获取第一条班级信息
                this.curClass = res.data[0]
                this.dialog.form.classId = res.data[0].classId
                // 实现节点的高亮效果,确保当前节点已经渲染完毕
                this.$nextTick(() => {
                    // 等页面加载完毕再去执行当前函数,类似于window.onload
                    this.$refs['classTreeRef'].setCurrentKey(res.data[0].classId)
                })
                this.getListStudent()
            })
        },

        // 获取学生列表
        getListStudent(query = {}) {
            //不要把多余的参数传给后端
            const { classId } = this.curClass
            const { total, ...rest } = this.paginate
            listStudents({ ...rest, classId, ...query }).then(res => {
                console.log("学生", res);
                this.stuList = res.data.rows
                this.paginate.total = res.data.count
            })
        },

        // 搜索功能
        handleQuery() {
            const hasInput = checkQueryInput(this.queryForm)
            if (!hasInput) return this.$message.warning("当前没有输入值，请至少输入一项数据!!")
            this.paginate.pageNum = 1
            this.getListStudent(this.queryForm)
        },

        // 节点重置
        rest() {
            console.log(restForm);
            restForm(this.$refs['queryFormRef'])
            // 回到第一页
            this.paginate.pageNum = 1
            this.getListStudent()
        },

        // 分页
        handleCurrentPage() {
            this.getListStudent(this.queryForm)
        },

        // 获取节点点击操作
        handleTreeClick(data, node, cpn) {
            console.log(data);
            // 更新当前班级信息
            this.curClass = data
            this.dialog.form.classId = data.classId
            // 更新学生信息
            this.getListStudent()
        },

        // 添加
        handleAdd() {
            this.dialog.visible = true
            this.dialog.isEdit = false
        },

        // 编辑
        handleEdit(row) {
            this.dialog.visible = true
            this.dialog.isEdit = true

            // Dialog的内容是懒渲染的，第一次打开弹窗的时候，会把表单的值作为初始值
            // restFields  将所有字段重置为初始值
            // 先点击添加再点击编辑  将所有字段重置为undefined
            // 先编辑再添加 form表单重新赋值 把第一次回显的数据作为初始值重置

            // 对象，直接赋值浅拷贝
            this.$nextTick(() => {
                this.dialog.form = JSON.parse(JSON.stringify(row))
            })
        },

        //提交
        handleSubmit() {
            this.$refs["dialogFormRef"].validate(valid => {
                console.log("未通过校验", valid);

                if (!valid) return

                const { form, isEdit } = this.dialog
                const { classInfo, createTime, majorInfo, stuId, updateTime, ...rest } = form
                const params = {
                    ...rest,
                    stuId: isEdit ? stuId : undefined
                }

                //判断是否是编辑状态
                const apiCall = this.dialog.isEdit ? updateStudents : addStudents

                apiCall(params).then(res => {
                    this.$message.success(res.msg)
                    // 更新学生信息
                    this.getListStudent()
                    this.handleClose()
                })
            })
        },

        // 关闭弹窗
        handleClose() {
            //关闭弹窗
            this.dialog.visible = false
            //清空表单
            restForm(this.$refs['dialogFormRef'])
        },


        // 删除
        handleDelete(row) {
            console.log(row);

            const { stuName, stuId } = row
            this.$confirm(`确定删除学生【${stuName}】吗？`, "提示", {
                type: "warning",
                confirmButtonText: "确定",
                cancelButtonText: "取消",
            }).then(() => {
                //确定
                delStudents(stuId).then((res) => {
                    console.log(res);
                    this.$message.success(res.msg)
                    //更新学生信息
                    this.getListStudent()
                })
            }).catch(() => {
                //取消
            })
        }

    },
}
</script>

<style lang="scss" scoped></style>